'use strict';
var server = require('../../server');

module.exports = function (Organization) {
    Organization.findPositionByOrgId = function (queryCon, response) {
        // var Personnel = server.models.Personnel;
        let query = queryCon ? JSON.parse(queryCon) : {};
        let positions = [];
        let where = {};
        // 模糊查询
        if (query.searchKey) {
            let searchKey = [];
            Object.keys(query.searchKey).map(key => {
                searchKey.push({
                    [key]: { like: query.searchKey[key] }
                })
            })
            if (searchKey.length) {
                where.or = searchKey;
            }
        }
        let newQueryObj = {
            "include": {
                "relation": "positions",
                "scope": {
                    "where": where,
                    "include": [
                        {
                            "relation": "org",
                        },
                        {
                            "relation": "user",
                            "scope": {
                                "include":
                                    {
                                        "relation": "person",
                                    }
                            }
                        }
                    ]
                }
            }
        };
        Organization.find(newQueryObj, function (err, data) {
            if (err) {
                response(err);
            }
            else {
                positions = data ? findChildrenTree(data, query.orgId) : [];

                //找到自己的positions信息
                let orgSelf = data.find((item) => {
                    item = item.toJSON();
                    if (item.id.toString() === query.orgId) {
                        return item;
                    }
                })
                let positionsSelf = [];
                if (orgSelf) {
                    orgSelf = orgSelf.toJSON();
                    positionsSelf = orgSelf.positions.map(per => {
                        return Object.assign(per, {
                            org: {
                                id: orgSelf.id,
                                name: orgSelf.name,
                                org_code: orgSelf.org_code,
                            }
                        })
                    })
                }

                positions = [...positionsSelf, ...positions];
                response(null, positions)
                // Organization.findOne({where:{id: orgid},include:['positions']}, function(err, oneOrg){
                //     if(err){
                //         response(err);
                //     }else{
                //         let oneOrgData = oneOrg.toJSON();
                //         oneOrgData.positions.map(per=>{
                //             return Object.assign(per,{
                //                 org:{
                //                     id:oneOrgData.id,
                //                     name:oneOrgData.name,
                //                     org_code:oneOrgData.org_code,
                //                 }
                //             })
                //         })
                //         positions = [...oneOrgData.positions,...positions];
                //         response(null,positions)
                //     }
                // })
            }
        })
    };
    Organization.remoteMethod(
        "findPositionByOrgId",
        {
            description: 'Query the all positions by the query.',
            accepts: [
                { arg: 'query', type: 'string', required: true, http: { source: 'path' } }
            ],
            returns: { type: 'array', root: true },
            http: { verb: 'GET', path: '/findPositionByOrgId/:query' }
        }
    );

    // subAreaAndBedsInfo

    Organization.subAreaAndBedsInfo = function (queryCon, response) {
        let query = queryCon ? JSON.parse(queryCon) : {};

        Organization.findOne({ "where": { "id": query.orgId } }, function (err, data) {
            if (err) {
                response(err);
            } else {
                let where = {};

                if (data.organization_type === "1") {
                    where = { "id": query.orgId };
                } else if (data.organization_type === "0") {
                    where = { "parentId": query.orgId, "organization_type": "1" };
                }

                let newQueryObj = {
                    "where": where,
                    "include": {
                        "relation": "areas",
                        "scope": {
                            "include": {
                                "relation": "rooms",
                                "scope": {
                                    "include": {
                                        "relation": "beds"
                                    }
                                }
                            }
                        }
                    }
                };
                Organization.find(newQueryObj, function (err, data) {
                    if (err) {
                        response(err);
                    }
                    else {
                        let subOrgs = [];
                        let subAreas = [];
                        let subRooms = [];
                        let subBeds = [];
                        data.forEach(eachOrg => {
                            const orgObj = eachOrg.toJSON();
                            subOrgs = subOrgs.concat(orgObj);
                            subAreas = subAreas.concat(orgObj.areas);
                            let orgSubBeds = [];
                            orgObj.areas.forEach(eachArea => {
                                let areaSubBeds = [];

                                eachArea.rooms.forEach(eachRoom => {
                                    subBeds = subBeds.concat(eachRoom.beds);
                                    areaSubBeds = areaSubBeds.concat(eachRoom.beds);
                                });
                                const areaBedsInfo = getBedsInfo(areaSubBeds);
                                eachArea.bedsInfo = areaBedsInfo;

                                subRooms = subRooms.concat(eachArea.rooms);
                                orgSubBeds = orgSubBeds.concat(areaSubBeds);
                            });
                            const orgBedsInfo = getBedsInfo(orgSubBeds);
                            orgObj.bedsInfo = orgBedsInfo;
                        });
                        const bedsInfo = getBedsInfo(subBeds);

                        response(null, { subOrgs, subAreas, subRooms, subBeds, bedsInfo });
                    }
                });
            }
        });
    };
    Organization.remoteMethod(
        "subAreaAndBedsInfo",
        {
            description: 'Fetch all includes Areas & BedsInfo by the OrganizationId.',
            accepts: [
                { arg: 'query', type: 'string', required: true, http: { source: 'path' } }
            ],
            returns: { type: 'array', root: true },
            http: { verb: 'GET', path: '/subAreaAndBedsInfo/:query' }
        }
    );

    Organization.allOrgAndItsBedsInfo = function (response) {
        const query = {
            "where": { "organization_type": "1" },
            "include": {
            "relation": "areas",
            "scope": {
                "include": {
                    "relation": "rooms",
                    "scope": {
                        "include": {
                            "relation": "beds"
                        }
                    }
                }
            }
        }};
        Organization.find(query, function (err, data) {
            if (err) {
                response(err);
            } else {
                data.forEach(eachOrg => {
                    const orgObj = eachOrg.toJSON();
                    let orgSubBeds = [];
                    orgObj.areas.forEach(eachArea => {
                        eachArea.rooms.forEach(eachRoom => {
                            orgSubBeds = orgSubBeds.concat(eachRoom.beds);
                        });
                    });
                    const orgBedsInfo = getBedsInfo(orgSubBeds);
                    eachOrg.bedsInfo = orgBedsInfo;
                });
                response(null, data);
            }
        });
    };

    Organization.remoteMethod(
        "allOrgAndItsBedsInfo",
        {
            description: 'Fetch all Org & Its BedsInfo',
            returns: { type: 'array', root: true },
            http: { verb: 'GET', path: '/allOrgAndItsBedsInfo' }
        }
    );

    function findChildrenTree(arr, findId) {
        var positions = [], lev = 0;
        var forFn = function (arr, id, lev) {
            for (var i = 0; i < arr.length; i++) {
                var item = arr[i].toJSON();
                item.id = item.id.toString();
                let idd = item.parentId ? item.parentId.toString() : null;
                if (idd === id) {
                    item.lev = lev;
                    item.positions.map(per => {
                        return Object.assign(per, {
                            org: {
                                id: item.id,
                                name: item.name,
                                org_code: item.org_code,
                            }
                        })
                    })
                    positions = [...positions, ...item.positions];
                    forFn(arr, item.id, lev + 1);
                }
            }
        };
        forFn(arr, findId, lev);
        return positions;
    }

    function getBedsInfo(bedList) {
        const _bedsInfo = {
            total: 0,
            using: 0,
            free: 0,
            reserving: 0,
        };
        _bedsInfo.total = bedList.length;
        bedList.forEach(eachBed => {
            if (eachBed.status === '0') {
                _bedsInfo.free += 1;
            } else if (eachBed.status === '1') {
                _bedsInfo.using += 1;
            } else if (eachBed.status === '2') {
                _bedsInfo.reserving += 1;
            }
        });
        return _bedsInfo;
    }
};
